import { useState, useEffect, useCallback } from "react";
import { message } from "antd";
import { getAnimationList } from "@/services/create-project/index";
import { default_animations_single } from "@/config";

// 获取文本动画数据的自定义Hook
export const useTextAnimationManager = ({}: AnimationManagerProps = {}) => {
  // 动画数据
  const [animationData, setAnimationData] = useState<AnimationData | null>(
    null,
  );

  // 是否正在加载动画效果
  const [loadingAnimations, setLoadingAnimations] = useState(false);

  // 默认的效果
  const [introAnimation, setIntroAnimation] = useState<string>("渐显");
  const [outroAnimation, setOutroAnimation] = useState<string>("渐隐");
  const [loopAnimation, setLoopAnimation] = useState<string>("跳动");

  // 获取动画数据
  const fetchAnimations = useCallback(async () => {
    setLoadingAnimations(true);
    try {
      // 获取动画列表
      const response: any = await getAnimationList();
      if (!response || !response.data) {
        throw new Error("获取动画列表失败，响应数据为空");
      }
      if (!response.data.success) {
        message.error("获取动画列表失败");
        // 设置默认值
        setAnimationData(default_animations_single);

        return;
      }
      const data = response.data.data;
      setAnimationData(data);
    } catch (error) {
      // 失败的情况下设置默认值
      message.error("获取动画列表失败");
      setAnimationData(default_animations_single);
    } finally {
      setLoadingAnimations(false);
    }
  }, []);

  // 组件挂载时获取动画数据
  useEffect(() => {
    fetchAnimations();
  }, [fetchAnimations]);

  return {
    animationData,
    loadingAnimations,
    introAnimation,
    outroAnimation,
    loopAnimation,
    setIntroAnimation,
    setOutroAnimation,
    setLoopAnimation,
    refetchAnimations: fetchAnimations,
  };
};
